﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Messaging.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class MessageController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState, ValidateInput(false)]
        public ActionResult Create(Guid senderID,
            string from,
            string to,
            string bccTo,
            string replyTo,
            string subject,
            string text,
            string[] flags)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateMessage", new
                {
                    SenderID = senderID,
                    From = HtmlUtility.StripTags(from),
                    To = HtmlUtility.StripTags(to),
                    BccTo = HtmlUtility.StripTags(bccTo),
                    ReplyTo = HtmlUtility.StripTags(replyTo),
                    Subject = HtmlUtility.StripTags(subject),
                    Text = HtmlUtility.Encode(text),
                    SendAttemptCount = 0,
                    Flags = flags.Merge(",")
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetMessage", new
            {
                EntityID = id,
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState, ValidateInput(false)]
        public ActionResult Update(int id, 
            string from,
            string to,
            string bccTo,
            string replyTo,
            string subject,
            string text,
            int sendAttemptCount,
            string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateMessage", new
                {
                    EntityID = id,
                    From = HtmlUtility.StripTags(from),
                    To = HtmlUtility.StripTags(to),
                    BccTo = HtmlUtility.StripTags(bccTo),
                    ReplyTo = HtmlUtility.StripTags(replyTo),
                    Subject = HtmlUtility.StripTags(subject),
                    Text = HtmlUtility.Encode(text),
                    SendAttemptCount = sendAttemptCount,
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteMessage", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page, 
            int? rows, 
            string sord, 
            string sidx,
            string searchTerm,
            string from,
            string to,
            string createdFrom,
            string createdTo,
            string sentFrom,
            string sentTo,
            string flagMask)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchMessages", new
            {
                Term = new
                {
                    Expression = searchTerm
                },
                From = new
                {
                    Expression = from
                },
                To = new
                {
                    Expression = to
                },
                FlagMask = flagMask,
                CreatedFrom = String.IsNullOrWhiteSpace(createdFrom) ? (DateTime?)null : Svc.DateTime(createdFrom),
                CreatedTo = String.IsNullOrWhiteSpace(createdTo) ? (DateTime?)null : Svc.DateTime(createdTo),
                SentFrom = String.IsNullOrWhiteSpace(sentFrom) ? (DateTime?)null : Svc.DateTime(sentFrom),
                SentTo = String.IsNullOrWhiteSpace(sentTo) ? (DateTime?)null : Svc.DateTime(sentTo),
                Index = page * rows,
                Count = rows,
                SortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Extended"
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.String(i.From),
                    JDM.String(i.To),
                    JDM.String(i.Subject),
                    Svc.DateTime((DateTime)JDM.DateTime(i.CreatedOn)),
                    i.SentOn != null ? Svc.DateTime((DateTime)JDM.DateTime(i.SentOn)) : String.Empty
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        [HttpPost]
        public ActionResult Senders()
        {
            dynamic m = Svc.ProcessOperation("ListMessageSenders");
            var data = new List<Object>();

            foreach(var i in m)
            {
                data.Add(new
                {
                    id = JDM.Guid(i.ID),
                    value = JDM.String(i.Name)
                });
            }
            return Json(data.ToArray());
        }

        #endregion
    }
}
